<template>
  <div class="box">
    <h1>登录页面</h1>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="ruleForm.mobile" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="showAddUser()">注册</el-button>
      </el-form-item>
    </el-form>
    <!-- 用户注册 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="用户注册" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="regRules">
          <el-form-item
            label="用户名称"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input v-model="form.username" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="手机号"
            :label-width="formLabelWidth"
            prop="mobile"
          >
            <el-input v-model="form.mobile" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="验证码"
            :label-width="formLabelWidth"
            prop="code"
          >
            <el-input
              v-model="form.code"
              autocomplete="off"
              style="width: 60%"
            />
            &emsp;&emsp;
            <el-button type="success" @click="submitSendForm(ruleFormRef)"
              >发送验证码</el-button
            >
          </el-form-item>
          <el-form-item
            label="密码"
            :label-width="formLabelWidth"
            prop="password"
          >
            <el-input v-model="form.password" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitRegForm(ruleFormRef)">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import { userLogin, sendCode, userReg } from "@/api/api";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { ru } from "element-plus/es/locales.mjs";
import { useRouter } from "vue-router";

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const ruleFormRef = ref<FormInstance>();
const router = useRouter();
interface RuleForm {
  mobile: string;
  password: string;
}
const form = ref({
  code: "",
  mobile: "",
  password: "",
  username: "",
});
const ruleForm = ref({
  mobile: "",
  password: "",
});
//注册框
const showAddUser = () => {
  dialogFormVisible.value = true;
};

//注册参数校验
const regRules = ref<FormRules>({
  username: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});
//登录参数校验
const rules = reactive<FormRules<RuleForm>>({
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
});

//发送验证码
const submitSendForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validateField(["mobile"], (valid) => {
    if (valid) {
      console.log("submit!");
      sendCode(form.value.mobile).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("发送成功");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!");
    }
  });
};

//注册用户
const submitRegForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      userReg(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("注册成功");
          dialogFormVisible.value = false;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//用户登录
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      userLogin(ruleForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("登录成功");

          let user = res.data.data;
          let token = user.token;

          sessionStorage.setItem("user", JSON.stringify(user));
          sessionStorage.setItem("token", token);

          router.push("/home");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//取消
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
